using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using Cinemachine;
using TMPro;
using UnityEngine.Events;

public class GameManager : MonoBehaviour
{
    public Camera mainCam;
    public static GameManager instance;

    public GameObject playerPrefab;
    public Transform player;
    public Rigidbody2D[] playerRigidbody;
    //[HideInInspector]
    public Transform FirstPlayerSpawnPoint;
    public LayerMask PlayerMask;

    public GameObject IntroductionObject;
    [HideInInspector]
    public Vector3 playerStartCoordinates;

    public Transform SFXParent;
    public GameObject emptyAudioSource;

    public CinemachineVirtualCamera activeCam;

    public CinemachineBlendDefinition defaultCamBlend;

    public Material defaultUIMat;
    public Material UIEmi;

    public UnityEvent OnPlayerDied;

    public bool canSpawnPlayer;

    // Start is called before the first frame update
    void Awake()
    {

        if (GameObject.FindGameObjectsWithTag("GameManager").Length <= 1)
        {
            DontDestroyOnLoad(this);
            instance = this;

        }
        else
        {
            Destroy(gameObject);
        }

        SetPlayerPosition();
    }

    private void Start()
    {

        mainCam = Camera.main;


    }

    // Update is called once per frame
    void Update()
    {

        if (player == null && canSpawnPlayer)
        {
            if (GameObject.Find("Player(Clone)") != null)
            {
                player = GameObject.Find("Player(Clone)").transform;
                FirstPlayerSpawnPoint = GameObject.Find("FirstPlayerSpawn").transform;

            }
            else
            {
                Instantiate(playerPrefab, FirstPlayerSpawnPoint.position, Quaternion.identity);


            }

            canSpawnPlayer = true;
        }

        if(SFXParent == null)
        {
            SFXParent = GameObject.Find("SFX").transform;
        }
    }



    
    public void Die()
    {
        //SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        SetPlayerPosition();
        OnPlayerDied.Invoke();


        player.position = playerStartCoordinates;

        /*
        foreach (var item in playerRigidbody)
        {
            item.velocity = new Vector2();
        }*/
        Destroy(player.gameObject);
        //Invoke("BIBIBIBIBJ",2f); 

    }

    void BIBIBIBIBJ()
    {
        player.GetComponent<Rigidbody2D>().isKinematic = false;

    }

    public void Restart()
    {
        Die();
    }

    void SetPlayerPosition()
    {
        if (playerStartCoordinates == new Vector3())
        {
            playerStartCoordinates = FirstPlayerSpawnPoint.position;
        }

    }